// import dayjs from "dayjs";
import {
  TaskDetailGetPage,
  TaskGetTaskDetail,
  TaskGetPage,
  TaskSave,
  TaskDelete,
  TaskUpdate,
  GetAllModuleScoresByPlanId
} from "@/api/teacher/task";
import { emitter } from "@/utils/mitt";
import { GetAllPlan } from "@/api/teacher/plan";
import { getCurrentInstance } from '@vue/runtime-core';
import { GetSelectItemBySelectType } from "@/api/teacher/common";
import { type PaginationProps } from "@pureadmin/table";
import { reactive, ref, onMounted, nextTick, computed } from "vue";
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import { usetaskPass, TaskDetailList } from "@/store/modules/taskPass";
import qs from "qs";
export function usePlan() {
  const STaskList = reactive({
    planId: "",
    moduleId: ""
  });
  // 任务设置
  const form = reactive({
    // id: 0, //自增 0
    taskId: "0",
    planId: "0", // 计划ID
    moduleId: "", // 模块名称的  ‘A’ 'B'
    taskName: "", // 任务名称
    markId: 0,  // 默认 0
    remark: "", // 任务说明
    important: "",
    isTemplate: 0,
    isEdit: 0
  });

  const scoreArr = ref([
    {
      moduleName: '当前计划',
      score: 0,
      moduleId: "Z",
    },
    {
      moduleId: "A",
      score: 0,
      moduleName: "大数据处理"
    },
    {
      moduleId: "B",
      score: 0,
      moduleName: "征信"
    },
    {
      moduleId: "C",
      score: 0,
      moduleName: "银行"
    },
    {
      moduleId: "D",
      score: 0,
      moduleName: "证券"
    },
    {
      moduleId: "E",
      score: 0,
      moduleName: "保险"
    },
    {
      moduleId: "F",
      score: 0,
      moduleName: "金融监管"
    },
    {
      moduleId: "G",
      score: 0,
      moduleName: "供应链金融"
    }
  ])
  const [usetaskPass_, TaskDetailList_] = [usetaskPass(), TaskDetailList()];
  const currentInstance = getCurrentInstance()
  const multipleTableRef = ref();
  const dataList = ref<any>([]);
  const planList = ref<any>([]);
  const SelectItemList = ref<any>([]);
  const loading = ref(false);
  const addPanelVisible = ref(false);
  const updatePanelVisible = ref(false);
  const loadingTitle = ref(undefined);
  const propsDetails = ref();
  const isDisabled = ref(false)
  const rules = {
    moduleId: [
      {
        required: true,
        message: "请选择模块名称！",
        trigger: ["blur", "change"]
      }
    ],
    taskName: [
      {
        required: true,
        message: "请输入任务名称！",
        trigger: ["blur", "change"]
      }
    ],
    remark: [
      {
        required: true,
        message: "请填写任务说明",
        trigger: ["blur", "change"]
      }
    ]
  };
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      minWidth: 100
    },
    {
      label: "模块名称",
      prop: "selectName",
      minWidth: 200
    },
    {
      label: "任务名称",
      prop: "taskName",
      minWidth: 200
    },
    {
      label: "分值",
      prop: "score",
      minWidth: 80
    },
    {
      label: "任务说明",
      prop: "remark",
      minWidth: 180,
      cellRenderer: () => <span>双击查看详情</span>
    },
    {
      label: "重要提示",
      prop: "important",
      minWidth: 180,
      cellRenderer: () => <span>双击查看详情</span>
    },
    {
      label: "操作",
      fixed: "right",
      width: 180,
      slot: "operation"
    }
  ];

  async function handleUpdate(row: any | undefined) {
    if (!row && !STaskList.planId) {
      ElMessage.warning("请选择计划名称！");
      return
    }
    if (row) {
      const res = await TaskGetTaskDetail(qs.stringify({ taskId: row.taskId }))
      loadingTitle.value = "修改任务";
      isDisabled.value = true;
      if (res.success) {
        nextTick(() => {
          const { data } = res;
          form.taskId = data?.taskId;
          form.moduleId = data?.moduleId;
          form.taskName = data?.taskName;
          form.remark = data?.remark;
          form.important = data?.important;
          form.planId = data?.planId;
          form.isTemplate = data?.isTemplate;
          form.isEdit = data?.isEdit;
        });

      } else {
        ElMessage.error(res.msg)
      }
    } else {
      form.taskId = "0";
      isDisabled.value = false;
      form.remark = "";
      form.important = "";
      form.isTemplate = 0;
      form.planId = STaskList.planId; // 计划ID
      loadingTitle.value = "添加任务";
    }
    updatePanelVisible.value = true;


  }

  async function handleDelete(row) {
    ElMessageBox({
      title: '提示', //MessageBox 标题
      closeOnClickModal: false,
      message: '是否确定删除当前项?', //MessageBox 消息正文内容
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      const res = await TaskDelete({ id: row.taskId });
      if (res.success) {
        ElMessage({
          message: "删除成功",
          type: "success"
        });
        onSearch(0);
      } else {
        ElMessage({
          message: res.msg,
          type: "error"
        });
      }

    }).catch(() => { })

  }

  function handleSizeChange() {
    onSearch(0);
  }

  function handleCurrentChange() {
    onSearch(0);
  }

  // 查看详情
  async function ViewDetails(row: any) {
    nextTick(() => {
      usetaskPass_.data = row; // 任务详情
      propsDetails.value = row;
    });
    const res = {
      pageIndex: TaskDetailList_.currentPage,
      pageSize: TaskDetailList_.pageSize,
      taskId: row.taskId
    };
    const respone = await TaskDetailGetPage(qs.stringify(res));
    if (respone.success) {
      const { list, pageIndex, pageSize, totalCount } = respone.data;
      TaskDetailList_.data = list;
      TaskDetailList_.currentPage = pageIndex;
      TaskDetailList_.pageSize = pageSize;
      TaskDetailList_.total = totalCount;
    } else {
      TaskDetailList_.data = [];
    }
  }

  // 搜索
  async function onSearch(state: number) {
    if (STaskList.planId == "" && STaskList.moduleId !== "") {
      ElMessage.warning("请选择计划名称")
      return
    }

    // 点击搜索时页码传1 增删改时按接口内容搜索
    const currentPage = !state ? pagination.currentPage : 1;
    const row = {
      pageIndex: currentPage,
      pageCount: pagination.pageSize,
      ...STaskList
    };
    loading.value = true;
    usetaskPass_.data = {}; // 清空查看任务详情内容
    const data = await TaskGetPage(row);
    TaskDetailList_.data = []; // 清空任务明细列表
    if (data.success) {
      pagination.pageSize = data.data.pageSize;
      pagination.currentPage = data.data.pageIndex;
      pagination.total = data.data.totalCount;
      dataList.value = data.data.list;
      propsDetails.value = "";
      loading.value = false;
    } else {
      setTimeout(() => {
        loading.value = false;
      }, 3000);
      dataList.value = [];
    }
  }

  //添加计划
  const addPlan = (addDtoRef: FormInstance | undefined) => {
    (addDtoRef as any).validate(async valid => {
      if (!valid) return;
      let respone = null;
      if (form.taskId === "0") respone = await TaskSave(form);
      else respone = await TaskUpdate(form);
      if (respone.status === 200) {
        ElMessage({
          message: respone.msg,
          type: "success"
        });
        ClosePanelVisible(addDtoRef);
        onSearch(0);
      } else {
        ElMessage({
          message: respone.msg,
          type: "error"
        });
      }
    });
  };

  async function updatePlan() {
    const respone = await TaskSave(form);
    if (respone.success) {
      onSearch(0);
      updatePanelVisible.value = false;
      ElMessage({
        message: "修改成功",
        type: "success"
      });
    }
  }

  // 獲取計劃名稱
  async function GetAllPlans() {
    const respone = await GetAllPlan();
    if (respone.success) {
      planList.value = respone.data;
    }
    // console.log(planList.value);

  }

  //  获取模块列表
  async function GetSelectItemBySelectTypes() {
    const respone = await GetSelectItemBySelectType("MKMC");
    if (respone.success) {
      SelectItemList.value = respone.data;
    }
  }

  function ClosePanelVisible(row: FormInstance | undefined) {
    updatePanelVisible.value = false;
    row.resetFields();
  }

  const resetForm = formEl => {
    formEl.resetFields();
    updatePanelVisible.value = false;
  };

  emitter.on("View_Setting", (e) => {
    onSearch(0);
    handleShowScore()
    dataList.value.forEach((el, index) => {
      if (el.taskId == e.taskId) {
        // 选择行
        nextTick(() => {
          setTimeout(() => {
            const { setCurrentRow } = multipleTableRef.value.getTableRef();
            setCurrentRow(dataList.value[index]);
            ViewDetails(e)
          }, 300)

        })
      }
    })
  });


  const SettingIsEdit = computed(() => {
    const data = planList.value.filter((el, index) => el.planId == STaskList.planId);
    return data[0]?.isTemplate ? !(data[0]?.isEdit == 1) : false
  })
  // emitter.on("View_Details", e => {
  //   console.log("es02", e)
  //   ViewDetails(e);
  //   dataList.value.forEach((el, index) => {
  //     if (el.taskId == e.taskId) {
  //       console.log("123", multipleTableRef.value)
  //       multipleTableRef.value!.setCurrentRow(index)
  //     }
  //   })

  // });

  onMounted(() => {
    GetAllPlans();
    GetSelectItemBySelectTypes();

  });


  //切换计划展示分数
  async function handleShowScore() {
    const params = qs.stringify({ planId: STaskList.planId })
    let res = await GetAllModuleScoresByPlanId(params)
    if (res.success) {
      scoreArr.value.forEach(item => {
        item.score = 0
      })
      if (res.data.length) {
        let totalScore = 0
        res.data.forEach(item => {
          const foundItem = scoreArr.value.find(a => item.moduleId == a.moduleId)
          if (foundItem) {
            foundItem.score = item.score
            totalScore += item.score
          }
        })
        scoreArr.value[0].score = totalScore
      }
    }
  }

  return {
    form,
    loading,
    columns,
    dataList,
    planList,
    STaskList,
    propsDetails,
    isDisabled,
    pagination,
    loadingTitle,
    SelectItemList,
    addPanelVisible,
    multipleTableRef,
    updatePanelVisible,
    rules,
    onSearch,
    ViewDetails,
    SettingIsEdit,
    resetForm,
    handleUpdate,
    handleDelete,
    // SearcTaskList,
    handleSizeChange,
    ClosePanelVisible,
    handleCurrentChange,
    addPlan,
    updatePlan,
    handleShowScore,
    scoreArr
  };
}
